﻿using System;
using System.Collections;
using System.Configuration;
using System.Data;
using System.Linq;
using System.Web;
using System.Web.Security;
using System.Web.UI;
using System.Web.UI.HtmlControls;
using System.Web.UI.WebControls;
using System.Web.UI.WebControls.WebParts;
using System.Xml.Linq;
using ZLCMS.Business;
using ZLCMS.Business.DwzFrame;
using ZLCMS.Data.Model;
using NHibernate;
using System.Collections.Generic;
using ZLCMS.Business.Util;
using DotNet.Common.NHibernateUtil;
using NHibernate.Criterion;
using Newtonsoft.Json;
using ZLCMS.Business.WeixinService.Data;

namespace ZLCMS.Web.SystemManage.Weixin
{
    public partial class OptBlock2048 : System.Web.UI.Page
    {
        protected FrameHelper _framePage;

        protected string _userAccount;

        protected void Page_Load(object sender, EventArgs e)
        {
            _userAccount = UserKit.GetUserAccountFailLogin();

            //初始化DWZ控件
            _framePage = new FrameHelper(this);

            ReturnCode rtCode = null;
            
            using (ISession session = SessionFactoryHelper.CreateSession())
            {
                ITransaction tran = session.BeginTransaction();

                try
                {
                    rtCode = ExecBusiness(session, tran);

                    if (rtCode.statusCode == 200)
                    {
                        tran.Commit();
                    }
                    else
                    {
                        tran.Rollback();
                    }
                }
                catch (System.Exception ex)
                {
                    tran.Rollback();
                    rtCode = new ReturnCode() { statusCode = 300, message = "操作出错-" + ex.Message };
                }
            }

            _framePage.Alert(rtCode);
        }

        protected ReturnCode ExecBusiness(ISession session, ITransaction tran)
        {
            string opt = Request["opt"];

            int uid;

            if (!int.TryParse(Request["uid"], out uid))
            {
                return new ReturnCode() { statusCode = 300, message = "参数错误" };
            }

            if (!string.IsNullOrEmpty(opt))
            {
                if (opt == "open")
                {
                    WxGamesConfig gameDb = session.CreateCriteria<WxGamesConfig>().Add(Expression.Eq("Id", uid)).Add(Expression.Eq("GameType", "Block")).Add(Expression.Eq("OwnerAccount", _userAccount)).UniqueResult<WxGamesConfig>();

                    if (gameDb.Status != "SETTING" && gameDb.Status != "PAUSE")
                    {
                        return new ReturnCode() { statusCode = 300, message = "活动状态错误" };
                    }

                    if (HaveRunningGame(session))
                    {
                        return new ReturnCode() { statusCode = 300, message = "有活动正在进行中，请先暂停或结束活动，再启动本活动。" };
                    }

                    //采用一个简单的算法以保证生成随机数的不同
                    Random rand = new Random();

                    if (gameDb.Status == "SETTING")
                    {
                        try
                        {
                            IList<GameAwardItem> list = JsonConvert.DeserializeObject<IList<GameAwardItem>>(gameDb.AwardConfig);
                            foreach (GameAwardItem item in list)
                            {
                                for (int i=0; i < item.Counter; i++)
                                {
                                    session.Save(new WxGamesAward()
                                    {
                                        GameId = gameDb.Id,
                                        AwardCode = RandomNum(rand, 8),
                                        AwardLevel = item.Code,
                                        AwardName = item.Name,
                                        AwardStatus = "0",
                                        WxId = "",
                                        Telephone = "",
                                        Addr = "",
                                        ApplyDate = DateTime.Now,
                                        OwnerAccount = gameDb.OwnerAccount
                                    });
                                }
                            }
                        }
                        catch
                        {
                        	
                        }
                      
                    }

                    gameDb.Status = "RUNNING";

                    session.Update(gameDb);
                   
                }
                else if (opt == "pause")
                {
                    WxGamesConfig gameDb = session.CreateCriteria<WxGamesConfig>().Add(Expression.Eq("Id", uid)).Add(Expression.Eq("GameType", "Block")).Add(Expression.Eq("OwnerAccount", _userAccount)).UniqueResult<WxGamesConfig>();

                    if (gameDb.Status != "RUNNING")
                    {
                        return new ReturnCode() { statusCode = 300, message = "活动状态错误" };
                    }

                    gameDb.Status = "PAUSE";

                    session.Update(gameDb);
                }
                else if (opt == "close")
                {
                    WxGamesConfig gameDb = session.CreateCriteria<WxGamesConfig>().Add(Expression.Eq("Id", uid)).Add(Expression.Eq("GameType", "Block")).Add(Expression.Eq("OwnerAccount", _userAccount)).UniqueResult<WxGamesConfig>();

                    if (gameDb.Status != "RUNNING" && gameDb.Status != "PAUSE")
                    {
                        return new ReturnCode() { statusCode = 300, message = "活动状态错误" };
                    }

                    gameDb.Status = "END";
                  
                    session.Update(gameDb);
                }
                else
                {
                    return new ReturnCode() { statusCode = 300, message = "参数错误" };
                }
            }
            else
            {
                return new ReturnCode() { statusCode = 300, message = "参数错误" };
            }

            return new ReturnCode() { statusCode = 200, message = "操作成功!", navTabId = _framePage.NavTabId };
        }


        #region 实现随机验证码 + protected string RandomNum(Random rand,int n)
        /// <summary>
        /// 实现随机验证码
        /// </summary>
        /// <param name="n">显示验证码的个数</param>
        /// <returns>返回生成的随机数</returns>
        protected string RandomNum(Random rand, int n) //
        {
            //定义一个包括数字、大写英文字母和小写英文字母的字符串
            string strchar = "0,1,2,3,4,5,6,7,8,9,A,B,C,D,E,F,G,H,I,J,K,L,M,N,O,P,Q,R,S,T,U,V,W,X,Y,Z,a,b,c,d,e,f,g,h,i,j,k,l,m,n,o,p,q,r,s,t,u,v,w,x,y,z";

            //将strchar字符串转化为数组
            //String.Split 方法返回包含此实例中的子字符串（由指定Char数组的元素分隔）的 String 数组。
            string[] VcArray = strchar.Split(',');
            string VNum = "";

            //记录上次随机数值，尽量避免产生几个一样的随机数
            int temp = -1;

            for (int i = 1; i < n + 1; i++)
            {
                if (temp != -1)
                {
                    //unchecked 关键字用于取消整型算术运算和转换的溢出检查。
                    //DateTime.Ticks 属性获取表示此实例的日期和时间的刻度数。
                    rand = new Random(i * temp * unchecked((int)DateTime.Now.Ticks));

                }

                //Random.Next 方法返回一个小于所指定最大值的非负随机数。
                int t = rand.Next(61);

                if (temp != -1 && temp == t)
                {
                    return RandomNum(rand,n);
                }

                temp = t;
                VNum += VcArray[t];

            }
            return VNum;//返回生成的随机数
        } 
        #endregion

        #region 检查是否有正在运行的同类游戏 + protected bool HaveRunningGame(ISession session)
        /// <summary>
        /// 检查是否有正在运行的同类游戏
        /// </summary>
        /// <param name="session"></param>
        /// <returns></returns>
        protected bool HaveRunningGame(ISession session)
        {
            object obj = session.CreateCriteria<WxGamesConfig>().Add(Expression.Eq("Status", "RUNNING")).Add(Expression.Eq("GameType", "Block")).Add(Expression.Eq("OwnerAccount", _userAccount)).SetProjection(Projections.RowCount()).UniqueResult();

            int count = 0;

            if (int.TryParse(obj.ToString(), out count))
            {
                if (count > 0)
                {
                    return true;
                }
            }

            return false;
        } 
        #endregion
    }
}